package com.fescoservice.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.fescoservice.exception.FSException;
import com.fescoservice.model.Category;
import com.fescoservice.model.CategoryId;

/**
 * A data access object (DAO) providing persistence and search support for
 * Category entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.fescoservice.dao.Category
 * @author MyEclipse Persistence Tools
 */

public class CategoryDAO extends HibernateDaoSupport {
	private static final Logger log = LogManager.getLogger(CategoryDAO.class);
	// property constants
	public static final String CODE1_NAME = "code1Name";
	public static final String CODE2_NAME = "code2Name";
	public static final String CODE3_NAME = "code3Name";
	public static final String USER_ID = "userId";
	public static final String LOCALE = "locale";
	public static final String TYPE = "type";
	public static final String STATUS = "status";

	protected void initDao() {
		// do nothing
	}

	public void save(Category transientInstance) {
		log.debug("saving Category instance");
		try {
			getHibernateTemplate().saveOrUpdate(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	
	
	public void update(Category transientInstance) {
		log.debug("saving Category instance");
		try {
			getHibernateTemplate().update(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delCategories(final String hql,final String boardcode1,final String boardcode2,final String boardcode3) throws FSException{
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws SQLException,
					HibernateException {
					Query q = session.createQuery(hql);
					   //q.setString("language" , language);   
					   q.setString("boardCode1" , boardcode1);   
					   if(!"FM0000".equals(boardcode2)){
						   q.setString("boardCode2" , boardcode2); 					   
					   }
					   if(!"FB0000".equals(boardcode3)){
						   q.setString("boardCode3" , boardcode3); 	
					   }
					q.executeUpdate();
				return null;
			}
		});

	}
	
	public void delete(Category persistentInstance) {
		log.debug("deleting Category instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Category findById(CategoryId id) {
		log.debug("getting Category instance with id: " + id);
		try {
			Category instance = (Category) getHibernateTemplate().get(
					"com.fescoservice.model.Category", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public Long countCategories(final String sql) throws FSException{
		log.debug("finding Category instance by example");
		try {
			Long count = (Long) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   SQLQuery q = session.createSQLQuery(sql);
						 //  q.setDate("enddate" , endDate); //endDate java.sql.Date   
						   log.debug("~~~~~~~~~L89~~~~~~~~~~~~~~~~~`````"); 
						  return q.addScalar( "cnt" , Hibernate.LONG).uniqueResult();
					   }
					 } );
			return count;
		} catch (Exception re) {
			log.error("count categories failed", re);
			throw new FSException("FS_ERROR_COUNTCATGORY",re.getMessage());
		}
	}
	
	public Long countCode1Name(final String sql,final String boardCode1) throws FSException{
		log.debug("finding Category instance by example");
		try {
			Long count = (Long) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   SQLQuery q = session.createSQLQuery(sql);
						   //q.setString(0, boardCode1); 
						  return q.addScalar( "cnt" , Hibernate.LONG).uniqueResult();
					   }
					 } );
			return count;
		} catch (Exception re) {
			log.error("count categories failed", re);
			throw new FSException("FS_ERROR_COUNTCATGORY",re.getMessage());
		}
	}
	
	public List getCode1Names(final String hql,final String language)  throws FSException{
		try {
			List result = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
						   q.setString("language" , language);   
						   q.setString("boardCode2" , "FM0000");   
						   q.setString("boardCode3" , "FB0000");   
						  return q.list();
					   }
					 } );
			return result;
		} catch (RuntimeException re) {
			log.error("get code1names failed", re);
			throw new FSException("FS_ERROR_GETCODE2NAMES",re.getMessage());
		}
	}
	
	public List getCode2Names(final String hql,final String language,final String boardCode1)  throws FSException{
		try {
			List result = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
						   q.setString("language" , language);   
						   q.setString("boardCode1" , boardCode1);   
						   q.setString("boardCode3" , "FB0000");   
						  return q.list();
					   }
					 } );
			return result;
		} catch (RuntimeException re) {
			log.error("get code2names failed", re);
			throw new FSException("FS_ERROR_GETCODE2NAMES",re.getMessage());
		}
	}
	
	public List getCode3Categories(final String hql,final String language,final String boardCode1,final String boardCode2)  throws FSException{
		try {
			List result = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
						   q.setString("language" , language);   
						   q.setString("boardCode1" , boardCode1);  
						   if(!"FM0000".equals(boardCode2)){
							   q.setString("boardCode2" , boardCode2);   
						   }						   
						  return q.list();
					   }
					 } );
			return result;
		} catch (RuntimeException re) {
			log.error("get Code3Categories failed", re);
			throw new FSException("FS_ERROR_GETCODE2NAMES",re.getMessage());
		}
	}

	public List findByExample(Category instance) {
		log.debug("finding Category instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Category instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Category as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByCode1Name(Object code1Name) {
		return findByProperty(CODE1_NAME, code1Name);
	}

	public List findByCode2Name(Object code2Name) {
		return findByProperty(CODE2_NAME, code2Name);
	}

	public List findByCode3Name(Object code3Name) {
		return findByProperty(CODE3_NAME, code3Name);
	}

	public List findByUserId(Object userId) {
		return findByProperty(USER_ID, userId);
	}

	public List findByLocale(Object locale) {
		return findByProperty(LOCALE, locale);
	}

	public List findByType(Object type) {
		return findByProperty(TYPE, type);
	}

	public List findByStatus(Object status) {
		return findByProperty(STATUS, status);
	}

	public List findAll() {
		log.debug("finding all Category instances");
		try {
			String queryString = "from Category";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Category merge(Category detachedInstance) {
		log.debug("merging Category instance");
		try {
			Category result = (Category) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Category instance) {
		log.debug("attaching dirty Category instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Category instance) {
		log.debug("attaching clean Category instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static CategoryDAO getFromApplicationContext(ApplicationContext ctx) {
		return (CategoryDAO) ctx.getBean("CategoryDAO");
	}
}